package scripting;

import client.MapleClient;
import lombok.extern.slf4j.Slf4j;
import tools.EncodingDetect;
import tools.MaplePacketCreator;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * @author cc
 */
@Slf4j
public abstract class AbstractScriptManager {

    private static ScriptEngineManager sem = new ScriptEngineManager();


    protected Invocable getInvocable(String path, MapleClient c) {
        return this.getInvocable(path, c, false);
    }

    protected Invocable getInvocable(String path, MapleClient c, boolean npc) {
        path = "scripts/" + path;
        ScriptEngine engine = null;
        if (c != null) {
            engine = c.getScriptEngine(path);
        }
        if (engine == null) {
            File scriptFile = new File(path);
            if (!scriptFile.exists()) {
                return null;
            }
            engine = sem.getEngineByName("graal.js");
            if (c != null) {
                c.setScriptEngine(path, engine);
            }
            try (InputStreamReader reader = new InputStreamReader(new FileInputStream(scriptFile), EncodingDetect.getJavaEncode(scriptFile))) {
                engine.eval(reader);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("Error executing script. Path: {} \nException \" {}", path, e);
                return null;
            }
        } else if (npc) {
            NPCScriptManager.getInstance().dispose(c);
            c.sendPacket(MaplePacketCreator.enableActions());
        }
        return (Invocable) engine;
    }
}
